var formTree;		// 表单树
var tabArea;		// 中心区域，用于打开表单
var validReg = new RegExp("^[A-Za-z0-9_]+$");
var foldMenu;		// 目录上的右键菜单
var foldMenu_newFold;
var foldMenu_newForm;
var foldMenu_rename;
var foldMenu_delete;
var formMenu;		// 表单上的右键菜单
var formMenu_rename;
var formMenu_delete;

var editFoldWindow;
var editFold_name;
var editFold_button;

var editFormWindow;
var editForm_name;
var editForm_button;

var menuCache = {};	// 目录缓存

// 关闭所有打开的form
function closeFormPanel(){
	var formArray = [];
	tabArea.items.each(function(item){
		if(item instanceof Wei.FormEditor){
			formArray.push(item);
		}
	});
	for(var i=0;i<formArray.length;i++){
		tabArea.remove(formArray[i], true);
	}
}

// 在指定节点上显示右键菜单
function showContextMenu(node, e){
	node.select();
	if (node.isLeaf()) {
		formMenu.sel_node = node;
		formMenu.showAt(e.getXY());
	} else {
		foldMenu_rename.setDisabled(node==formTree.root);
		foldMenu_delete.setDisabled(node==formTree.root);
		foldMenu.sel_node = node;
		foldMenu.showAt(e.getXY());
	}
}

// 打开表单
function openFormHandler(node){
	if(!node.isLeaf()){
		return ;
	}
	var formPath = node.attributes.folder_path;
	var editor = tabArea.items.find(function(sub){
		return (sub.formPath==formPath);
	});
	if(editor){
		tabArea.activate(editor);
	}else{
		var editor = new Wei.FormEditor({
			title: node.text,
			formPath: node.attributes.folder_path
		});
		tabArea.add(editor);
		tabArea.activate(editor);
	}
}

// 验证FoldName
function validFoldName(name){
	if(Ext.isEmpty(name)){
		editFold_name.markInvalid("目录名不能为空");
		return false;
	}
	if(!validReg.test(name)){
		editFold_name.markInvalid("目录名只能包含字母、数字和下划线");
		return false;
	}
	return true;
}

// 创建文件夹
function createFoldHandler(){
	editFoldWindow.sel_node = foldMenu.sel_node;
	editFoldWindow.setTitle("创建目录");
	editFold_name.setValue();
	editFold_button.setHandler(insertFoldHandler);
	editFoldWindow.show();
}

// 创建目录
function insertFoldHandler(){
	var name = editFold_name.getValue();
	if(!validFoldName(name)){
		return ;
	}
	var path = editFoldWindow.sel_node.attributes.folder_path;
	Ext.Ajax.request({
		url: "console?action=insertFold",
		success: function(response){
			if(response.responseText=="1"){
				editFoldWindow.sel_node.reload(function(node){
					var nn = node.findChild("text", name, false);
					nn.select();
				});
				editFoldWindow.setVisible(false);
			}else{
				editFold_name.markInvalid(response.responseText);
			}
		},
		params: {
			path: path,
			name: name
		}
	});
}

// 重命名文件夹
function renameFoldHandler(){
	editFoldWindow.sel_node = foldMenu.sel_node;
	editFoldWindow.setTitle("重命名目录");
	editFold_name.setValue(foldMenu.sel_node.text);
	editFold_button.setHandler(updateFoldHandler);
	editFoldWindow.show();
}

// 更新目录
function updateFoldHandler(){
	var name = editFold_name.getValue();
	if(!validFoldName(name)){
		return ;
	}
	var path = editFoldWindow.sel_node.attributes.folder_path;
	Ext.Ajax.request({
		url: "console?action=updateFold",
		success: function(response){
			if(response.responseText=="1"){
				editFoldWindow.sel_node.parentNode.reload(function(node){
					var nn = node.findChild("text", name, false);
					nn.select();
				});
				editFoldWindow.setVisible(false);
			}else{
				editFold_name.markInvalid(response.responseText);
			}
		},
		params: {
			path: path,
			name: name
		}
	});
}

// 删除文件夹
function deleteFoldHandler(){
	var text = foldMenu.sel_node.text;
	Ext.MessageBox.confirm("确认窗口", "你确定要删除目录："+text, function(btn){
		if(btn!="yes"){
			return ;
		}
		Ext.Ajax.request({
			url: "console?action=deleteFold",
			success: function(response){
				if(response.responseText=="1"){
					foldMenu.sel_node.parentNode.reload();
				}
			},
			params: {
				path: foldMenu.sel_node.attributes.folder_path
			}
		});
	});
}

// 验证FormName
function validFormName(name){
	if(Ext.isEmpty(name)){
		editForm_name.markInvalid("表单名不能为空");
		return false;
	}
	if(!validReg.test(name)){
		editForm_name.markInvalid("表单名只能包含字母、数字和下划线");
		return false;
	}
	return true;
}

// 创建form表单
function createFormHandler(){
	editFormWindow.sel_node = foldMenu.sel_node;
	editFormWindow.setTitle("创建表单");
	editForm_name.setValue();
	editForm_button.setHandler(insertFormHandler);
	editFormWindow.show();
}

// 插入form表单
function insertFormHandler(){
	var name = editForm_name.getValue();
	if(!validFormName(name)){
		return ;
	}
	var path = editFormWindow.sel_node.attributes.folder_path;
	Ext.Ajax.request({
		url: "console?action=insertForm",
		success: function(response){
			if(response.responseText=="1"){
				editFormWindow.sel_node.reload(function(node){
					var nn = node.findChild("text", name, false);
					nn.select();
				});
				editFormWindow.setVisible(false);
			}else{
				editForm_name.markInvalid(response.responseText);
			}
		},
		params: {
			path: path,
			name: name
		}
	});
}

// 重命名form表单
function renameFormHandler(){
	editFormWindow.sel_node = formMenu.sel_node;
	editFormWindow.setTitle("修改表单");
	editForm_name.setValue(formMenu.sel_node.text);
	editForm_button.setHandler(updateFormHandler);
	editFormWindow.show();
}

// 更新表单
function updateFormHandler(){
	var name = editForm_name.getValue();
	if(!validFormName(name)){
		return ;
	}
	var path = editFormWindow.sel_node.attributes.folder_path;
	Ext.Ajax.request({
		url: "console?action=updateForm",
		success: function(response){
			if(response.responseText=="1"){
				editFormWindow.sel_node.parentNode.reload(function(node){
					var nn = node.findChildBy(function(cn){
						if(cn.isLeaf() && cn.text==name){
							return true;
						}
					});
					if(nn){
						nn.select();
						updateFormEditor(path, nn);
					}
				});
				editFormWindow.setVisible(false);
			}else{
				editForm_name.markInvalid(response.responseText);
			}
		},
		params: {
			path: path,
			name: name
		}
	});
}

// 更新表单编辑器
function updateFormEditor(path, node){
	var fe = tabArea.items.find(function(item){
		if(item.formPath==path){
			return true;
		}
	});
	if(fe){
		fe.updatePath(node.attributes.folder_path, node.text);
	}
}

// 删除form表单
function deleteFormHandler(){
	var text = formMenu.sel_node.text;
	Ext.MessageBox.confirm("确认窗口", "你确定要删除表单："+text, function(btn){
		if(btn!="yes"){
			return ;
		}
		Ext.Ajax.request({
			url: "console?action=deleteForm",
			success: function(response){
				if(response.responseText=="1"){
					formMenu.sel_node.parentNode.reload();
				}
			},
			params: {
				path: formMenu.sel_node.attributes.folder_path
			}
		});
	});
}

// 初始化表单树
function initFormTree(){
	var tl = new Ext.tree.TreeLoader({
		dataUrl: "console?action=loadFormTree"
	});
	tl.on("beforeload", function(loader, node){
		loader.baseParams.folder_path = node.attributes.folder_path;
	});
	formTree = new Ext.tree.TreePanel({
		region: "west",
		margins: "2 0 2 2",
		animate: false,
		loader: tl,
		split: true,
		width: 180,
		tbar: [{
			text: "关闭表单",
			icon: ctx+"/weifly/images/delete.gif",
			handler: closeFormPanel
		}]
	});
	var root = new Ext.tree.AsyncTreeNode({
		text: "资料库",
		folder_path: "/",
		expanded: true
	});
	formTree.setRootNode(root);
	formTree.on("contextmenu", showContextMenu);
	formTree.on("dblclick", openFormHandler);
}

// 初始化中心区域
function initTabArea(){
	tabArea = new Ext.TabPanel({
		region: "center",
		margins: "2 2 2 0",
		activeTab: 0,
		items: [{
			title: "欢迎页",
			bodyStyle: "padding:10px;",
			html: "欢迎使用weifly构建平台"
		}]
	});
}

// 初始化树上的右键菜单
function initTreeMenu(){
	foldMenu_newFold = new Ext.menu.Item({
		text: "新建目录",
		icon: ctx+"/weifly/images/folder.gif",
		handler: createFoldHandler
	});
	foldMenu_newForm = new Ext.menu.Item({
		text: "新建表单",
		icon: ctx+"/weifly/images/form.gif",
		handler: createFormHandler
	});
	foldMenu_rename = new Ext.menu.Item({
		text: "重命名",
		handler: renameFoldHandler
	});
	foldMenu_delete = new Ext.menu.Item({
		text: "删除目录",
		icon: ctx+"/weifly/images/delete.gif",
		handler: deleteFoldHandler
	});
	foldMenu = new Ext.menu.Menu({
		items:[
			foldMenu_newFold,
			foldMenu_newForm,
			foldMenu_rename,
			foldMenu_delete
		]
	});
	formMenu_rename = new Ext.menu.Item({
		text: "重命名",
		handler: renameFormHandler
	});
	formMenu_delete = new Ext.menu.Item({
		text: "删除表单",
		icon: ctx+"/weifly/images/delete.gif",
		handler: deleteFormHandler
	});
	formMenu = new Ext.menu.Menu({
		items:[
			formMenu_rename,
			formMenu_delete
		]
	});
}

// 初始化编辑目录窗口
function initEditFoldWindow(){
	editFold_name = new Ext.form.TextField({
		fieldLabel: "目录名称",
		anchor: "100%"
	});
	editFold_button = new Ext.Button({
		text: "确 定"
	});
	editFoldWindow = new Ext.Window({
		layout: "form",
		closeAction: "hide",
		bodyStyle: "padding:10px;",
		labelWidth: 70,
		autoHeight: true,
		modal: true,
		width: 300,
		items: [editFold_name],
		buttons: [editFold_button,{
			text: "取 消",
			handler: function(){
				editFoldWindow.setVisible(false);
			}
		}]
	});
}

// 初始化编辑表单窗口
function initEditFormWindow(){
	editForm_name = new Ext.form.TextField({
		fieldLabel: "表单名称",
		anchor: "100%"
	});
	editForm_button = new Ext.Button({
		text: "确 定"
	});
	editFormWindow = new Ext.Window({
		layout: "form",
		closeAction: "hide",
		bodyStyle: "padding:10px;",
		labelWidth: 70,
		autoHeight: true,
		modal: true,
		width: 300,
		items: [editForm_name],
		buttons: [editForm_button,{
			text: "取 消",
			handler: function(){
				editFormWindow.setVisible(false);
			}
		}]
	});
}

// 获得节点对应的menu
function fetchNodeMenu(type){
	if(menuCache[type]){
		return menuCache[type];
	}
	var conf = [];
	var child = metaJson[type].child;
	if(child && child.length>0){
		var menuMap = {};
		var rootArr = [];
		for(var i=0;i<child.length;i++){
			var createAction = {
				text: child[i].type,
				item_type: child[i].type,
				handler: function(){
					var me = menuCache[type].form_editor;
					var node = menuCache[type].form_node;
					me.addItemNode(node, this.item_type);
				}
			};
			if(Ext.isEmpty(child[i].menu)){
				rootArr.push(createAction);
			}else{
				if(!menuMap[child[i].menu]){
					menuMap[child[i].menu] = {
						text: child[i].menu,
						menu:[]
					};
				}
				menuMap[child[i].menu].menu.push(createAction);
			}
		}
		for(var p in menuMap){
			conf.push(menuMap[p]);
		}
		for(var i=0;i<rootArr.length;i++){
			conf.push(rootArr[i]);
		}
		conf.push({
			text: "清空子",
			icon: ctx+"/weifly/images/clear.gif",
			handler: function(){
				var me = menuCache[type].form_editor;
				var node = menuCache[type].form_node;
				me.clearSubItem(node);
			}
		});
	}
	conf.push({
		text: "删除",
		icon: ctx+"/weifly/images/delete.gif",
		handler: function(){
			var me = menuCache[type].form_editor;
			var node = menuCache[type].form_node;
			me.delItemNode(node);
		}
	});
	menuCache[type] = new Ext.menu.Menu({
		items: conf
	});
	return menuCache[type];
}

Ext.onReady(function(){
	Ext.QuickTips.init();
	initFormTree();
	initTabArea();
	initTreeMenu();
	initEditFoldWindow();
	initEditFormWindow();
	var vp = new Ext.Viewport({
		layout: "border",
		items: [formTree, tabArea]
	});
});